package com.wys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.util.concurrent.AtomicDouble;
import com.wys.common.BaseContext;
import com.wys.dao.OrderDao;
import com.wys.dto.OrdersDto;
import com.wys.exception.CustomerException;
import com.wys.pojo.*;
import com.wys.result.R;
import com.wys.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     *  用户下单
     * @param orders
     */
    @Transactional
    @Override
    public void submit(Orders orders,HttpSession session) {
        //用户ID
        Long userId = BaseContext.getThreadLocal();
        //查询用户购物车
        List<ShoppingCart> shoppingCart = shoppingCartService.getShoppingCart(session);
        if(shoppingCart == null || shoppingCart.size() == 0){
            throw new CustomerException("当前购物车为空！");
        }

        //查看用户数据
        User user = userService.getById(userId);
        //查看地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook == null){
            throw  new CustomerException("收获地址为空！");
        }
        //订单ID
        long orderId = IdWorker.getId();
        //订单总金额
        AtomicDouble amount = new AtomicDouble(0);
        List<OrderDetail> orderDetailList = shoppingCart.stream().map((item) ->{
            OrderDetail orderDetail =new OrderDetail();
            orderDetail.setName(item.getName());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            orderDetail.setImage(item.getImage());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).doubleValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //向订单表插入数据

        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        orders.setConsignee(addressBook.getConsignee());
        this.save(orders);
        //向用户订单表插入数据
        orderDetailService.saveBatch(orderDetailList);
        //清空购物车
        shoppingCartService.deletedShoppingCart(session);
    }


    /**
     * 查看订单
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page getOrders(int page, int pageSize,HttpSession session) {
        //当前登录用户
        Long userId = (Long) session.getAttribute("user");
        //得到该用户的订单
        LambdaQueryWrapper<Orders> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(Orders::getUserId,userId);
        //按支付时间排序
        orderWrapper.orderByDesc(Orders::getCheckoutTime);
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        page(ordersPage,orderWrapper);
        //带具体菜品的订单分页
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //属性拷贝
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        //用户的所有订单
        List<Orders> orders = ordersPage.getRecords();
        //用户的订单具体详情
        List<OrdersDto> ordersDtoList = orders.stream().map((item) ->{
            OrdersDto ordersDto = new OrdersDto();
            //属性拷贝
            BeanUtils.copyProperties(item,ordersDto);
            //用户订单ID
            Long orderId = item.getId();
            //订单菜品集合
            LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
            orderDetailWrapper.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailWrapper);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtoList);
        return ordersDtoPage;
    }

    /**
     *  管理端查看订单
     * @param page
     * @param pageSize
     * @param number 订单编号
     * @param beginTime  开始日期
     * @param endTime    截至日期
     * @return
     */
    @Override
    public Page getUserPage(int page, int pageSize, String number, String beginTime, String endTime) {
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> ordersWrapper = new LambdaQueryWrapper<>();
        ordersWrapper.eq(number != null,Orders::getNumber,number);
        ordersWrapper.between(StringUtils.isNotEmpty(beginTime) || StringUtils.isNotEmpty(endTime),Orders::getOrderTime,beginTime,endTime);
        page(ordersPage,ordersWrapper);
        return ordersPage;
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @Override
    public R<String> getAgain(HttpSession session,Orders orders) {
       //订单ID
        Long id = orders.getId();
        //用户ID
        Long userID = (Long) session.getAttribute("user");
        //订单的具体菜品或套餐信息
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> orderDetailList = orderDetailService.list(wrapper);
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) ->{
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item,shoppingCart);
            shoppingCart.setUserId(userID);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCartList);
        return R.success("成功！");
    }

}
